package com.zyt.springboot.teach_segmentLock;

import java.util.concurrent.locks.ReentrantLock;

/*
 * 腾哥专用代码防伪标志！！！
 * @params: 分段锁技术
 */
public class SegmentLock {//代码实现分段锁的概念
    private final int segments;//分段的数量
    private final ReentrantLock[] locks;//锁数组

    public SegmentLock(int segments) {
        this.segments = segments;
        this.locks = new ReentrantLock[segments];
        //通过循环创建每个锁的锁对象
        for(int i = 0;i < segments;i ++){
            locks[i] = new ReentrantLock();
        }
    }

    public void acquireLock(Object key){//给指定key值上锁
        int segment = getSegment(key);
        locks[segment].lock();
    }

    public void releaseLock(Object key){//给指定key值解锁
        int segment = getSegment(key);
        locks[segment].unlock();
    }

    private int getSegment(Object key){
        //根据键的哈希值 和 分段数量 计算 段的索引
        //对key的哈希值用段的数量取模
        return Math.abs(key.hashCode()) % segments;
    }
}
